package com.zzptc.zzsgz.bdsjws.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;

import com.zzptc.zzsgz.bdsjws.MyApplication;
import com.zzptc.zzsgz.bdsjws.db.MobilelnfoDao;
import com.zzptc.zzsgz.bdsjws.vo.Contact;
import com.zzptc.zzsgz.bdsjws.vo.Mobilelnfo;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/4/23.
 */
//普通java类 没有上下文
public class MyUtils {
    //返回共享首选项对象
    public static SharedPreferences getpreferences() {
        //获取上下文 再获取共享首选项
        return MyApplication.getContext().getSharedPreferences("loginnew", Context.MODE_PRIVATE);

    }

    //首先判断是否存在SD卡
    public static boolean haveSD() {
        //状态是SD卡可读可写MEDIA_MOUNTED   nvironment环境 getExternalStorageState()外部存储器状态
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    //得到文件的路径
    public static File getDir() {
        if (haveSD()) {
            //getExternalStorageDirectory()   getDownloadCacheDirectory()
            return Environment.getExternalStorageDirectory();
        }
        return Environment.getDownloadCacheDirectory();
        //return Environment.getExternalStorageDirectory();
    }

    public static Intent getinstallApk(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        //MyApplication.getContext().startActivity(intent);
        return intent;
    }

    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    //获取版本号
    public static int getVersionCode(Context context)//获取版本号(内部识别号)
    {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }

    //拷贝外部数据库
    public static void copyFileToMobile(Context context, String dbname, String s) throws Exception {
        URL url = context.getClass().getClassLoader().getResource("assets/" + dbname);
        String dbfile = "/data/data/" + MyApplication.getContext().getPackageName() + "/database";
        File dbfileMobile = new File(dbfile);
        if (!dbfileMobile.exists()) {
            dbfileMobile.mkdir();
        } else {
            File dbfileMobilee = new File(dbfileMobile + "/" + dbname);
            if (!dbfileMobilee.exists()) {
                dbfileMobilee.createNewFile();

            }
            FileUtils.copyURLToFile(url, dbfileMobile);
        }
    }

    public static List<Contact> getAllContacts() {
        List<Contact> lists = new ArrayList<Contact>();
        ContentResolver contentProvider = MyApplication.getContext().getContentResolver();
        //Uri uri= ContactsContract.Contacts.CONTENT_URI;
        //Cursor cursor=contentProvider.query(uri,null,null,null,null);
        Cursor cursor = contentProvider.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                //Contact contact = new Contact();
                int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                int num = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                String phonenum = null;
                if (num > 0) {
                    phonenum = getPhonenumByID(id);
                }
                //获取手机归属地

                Contact contact = new Contact(id, name, phonenum,"");
                lists.add(contact);
            }
            cursor.close();
        }
        return lists;
    }

    public static String getAddressByTel(String tel) {
        String address = null;
        String[] aa = tel.split("");
        String newtel = tel.replace(" ", "").replace("-", "");
        String telnum = null;
        if (newtel.length() == 11 && newtel.matches("^1[3578]\\d{9}$")) {
            //手机号码
            telnum = newtel.substring(0, 7);
            address=getMobileAddrByTel(telnum);
        } else {
            //座机
            int length = newtel.length();
            switch (length) {
                case 10:
                    getZUOJIAddrByTel(newtel, 3);
                    break;
                case 11:
                    //分2种
                    address=getZUOJIAddrByTel(newtel,3);
                    if (address==null){
                        address=getZUOJIAddrByTel(newtel,4);
                    }
                    break;
                case 12:
                    address=getZUOJIAddrByTel(newtel,4);
                    break;
                default:
                    address="未知";
            }

        }
        return address;
    }

    public static String getZUOJIAddrByTel(String tel, int length) {
        Mobilelnfo mobileInfo = MyApplication.getMobiledaoSession().getMobilelnfoDao().queryBuilder()
                .where(MobilelnfoDao.Properties.AreaCode.eq(tel.substring(0, length))).limit(1).distinct().unique();
        return mobileInfo.getMobileArea();
    }

    public static String getMobileAddrByTel(String tel) {
        Mobilelnfo mobileInfo = MyApplication.getMobiledaoSession().getMobilelnfoDao().queryBuilder()
                .where(MobilelnfoDao.Properties.MobileNumber.eq(tel)).distinct().unique();
       return   mobileInfo.getMobileArea();
    }
    //根据id查询电话号码
    public static String getPhonenumByID(int id){
        String telnum=null;
        ContentResolver contentProvider=MyApplication.getContext().getContentResolver();
       Cursor cursor=contentProvider.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
               new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
               ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"=?",new String[]{id+""},null);
        if (cursor!=null){
            if (cursor.moveToNext()){
                telnum=cursor.getString(cursor.getColumnIndex
                        (ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
        }
        return  telnum;
    }
}
